package com.ray.service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ray.bean.CompanyMaterialTableBean;
import com.ray.bean.CompanyMaterialTypeBean;
import com.ray.bean.DatatablesViewPageBean;
import com.ray.bean.FeedOrderDetailBean;
import com.ray.bean.MyApplyBean;
import com.ray.bean.MyAuditBean;
import com.ray.bean.OrderInfoDetailBean;
import com.ray.exception.ServiceException;
import com.ray.mapper.CompanyMaterialMapper;
import com.ray.mapper.DingTalkMapper;
import com.ray.mapper.FeedOrderMapper;
import com.ray.mapper.OrderCreateApplyMapper;
import com.ray.mapper.OrderMapper;
import com.ray.mapper.PurchaseOrderMapper;
import com.ray.pojo.MyUser;
import com.ray.pojo.OrderInfoDetailPojo;
import com.ray.pojo.PurchaseOrderDetailPojo;
import com.ray.util.StringUtil;

/**
 * 投料单逻辑层
 * <p>
 * Title: FeedOrderService
 * </p>
 * <p> 
 * Description:
 * </p>
 * 
 * @author 李斌
 * @date 2018年10月11日
 */
@Service
public class FeedOrderService {

	@Autowired
	ProductionUnitFeedService productionUnitFeedService;
	@Autowired
	BasicDataService basicDataService;
	@Autowired
	CompanyMaterialService companyMaterialService;
	@Autowired
	CompanyMaterialTypeService companyMaterialTypeService;
	@Autowired
	DuplicateOrderUpdateRecordsService duplicateOrderUpdateRecordsService;
	@Autowired
	ApprovalService approvalService;
	@Autowired 
	OrderService orderService;
	@Autowired
	PurchaseOrderService purchaseOrderService;
	
	@Autowired
	CompanyMaterialMapper companyMaterialMapper;
	@Autowired
	FeedOrderMapper feedOrderMapper;
	@Autowired
	DingTalkMapper dingTalkMapper;
	@Autowired
	OrderMapper orderMapper;
	@Autowired
	OrderCreateApplyMapper orderCreateMapper;
	@Autowired
	PurchaseOrderMapper purchaseOrderMapper;

	/**
	 * 新增订单明细信息 @date 2018年10月11日 下午1:35:12 @author 李斌 @return void @throws
	 */
	public void addOrderInfoDetail(Map<String, String> map) {
		Assert.notNull(map.get("orderInfoDetail"), "订单信息为空");
		OrderInfoDetailBean orderInfoDetail = JSONObject.parseObject(map.get("orderInfoDetail"),
				OrderInfoDetailBean.class);
		Assert.isTrue(orderInfoDetail.getFeedTotal() != null && !orderInfoDetail.getFeedTotal().equals(""), "订单投料数为空");
		Assert.isTrue(orderInfoDetail.getMaterialType() != null && !orderInfoDetail.getMaterialType().equals(""),
				"物料类型为空");
		Assert.isTrue(orderInfoDetail.getMaterialFactory() != null && !orderInfoDetail.getMaterialFactory().equals(""),
				"仓位为空");
		//是否有相同的物料类型
		Map<String,Object>paramMap = new HashMap<String,Object>();
		paramMap.put("loginCompany", map.get("loginCompany"));
		List<OrderInfoDetailBean> oldOrderInfoDetailList = duplicateCheck(orderInfoDetail);
		boolean notHaveOrderDetail =oldOrderInfoDetailList==null || oldOrderInfoDetailList.size()==0;
		int isOpraterAdd = 0;
		int isReadColor = 0;
		//订单里面没有就直接写行号为-1
		if(notHaveOrderDetail) {
			orderInfoDetail.setLineNo("-1");
			isOpraterAdd = 1;
			// 校验该物料类型是否需要颜色
			Map<String, String> mateiralTypeMap = new HashMap<String, String>();
			mateiralTypeMap.put("loginCompany", map.get("loginCompany"));
			mateiralTypeMap.put("materialType", orderInfoDetail.getMaterialType());
			mateiralTypeMap.put("status", "1");
			CompanyMaterialTypeBean materialTreeBean = companyMaterialTypeService
					.getCompanyMaterialTypeByMateiralType(mateiralTypeMap);
			if (materialTreeBean != null) {
				isReadColor = materialTreeBean.getIsReadColor();
			}
		}else {
			//如果有并且最大行数大于0,就在最大行数上+1
//			int rowIndex = feedOrderMapper.getMaxRowByMaterialTypeAndFactory(orderInfoDetail);
//			if(rowIndex>0) {
//				rowIndex++;
//				orderInfoDetail.setLineNo(rowIndex+"");
//				//如果原订单明细里面有这个物料类型.那么下面的物料类型是否读取颜色就根据上面的来
//				isReadColor = oldOrderInfoDetailList.get(0).getIsReadColor();
//			}else {
//				throw new ServiceException("该物料类型已存在,请勿重复添加");
//			}
			throw new ServiceException("该物料类型已存在,请到制单页面添加");
		}
		orderInfoDetail.setIsOpraterAdd(isOpraterAdd);
		//给物料订单设置是否读取颜色
		orderInfoDetail.setIsReadColor(isReadColor);
		if (orderInfoDetail.getMaterialCode() == null || "".equals(orderInfoDetail.getMaterialCode())) {
			Assert.notNull(map.get("materialData"), "物料信息为空");
			CompanyMaterialTableBean companyMaterialTableBean = JSONObject.parseObject(map.get("materialData"),
					CompanyMaterialTableBean.class);
			// 判断物料类型
			Assert.isTrue(companyMaterialTableBean.getMaterialType() != null
					&& !companyMaterialTableBean.getMaterialType().equals(""), "物料类型为空");
			Assert.isTrue(companyMaterialTableBean.getDefaultWarehouse() != null
					&& !companyMaterialTableBean.getDefaultWarehouse().equals(""), "物料仓位为空");
			MyUser myuser = new MyUser();
			myuser.setCompany(map.get("loginCompany"));
			myuser.setUserId(map.get("loginUserId"));
			myuser.setUserName(map.get("loginUserName"));
			if(orderInfoDetail.getMaterialFactory().equals("2")) {
				companyMaterialTableBean.setDefaultWarehouse("辅料仓");
			}
			if(!"付".equals(companyMaterialTableBean.getUnit())) {
				companyMaterialTableBean.setIsEquals(0);
			}else {
				companyMaterialTableBean.setIsEquals(1);
			}
			/*if(isReadColor==2) {
				companyMaterialTableBean.setColor(null);
				companyMaterialTableBean.setColorDescription(null);
			}*/
			this.isEqualIsReadColorByMaterialType(companyMaterialTableBean, orderInfoDetail, paramMap);
			List<CompanyMaterialTableBean> list = basicDataService.insertCompanyMaterial(companyMaterialTableBean,
					myuser);
			Assert.isTrue(list != null && list.size() > 0, "添加物料失败");
			map.put("id", list.get(0).getId());
			List<CompanyMaterialTableBean> companyMaterialList = basicDataService.getCompanyMaterialDetail(map);
			Assert.isTrue(companyMaterialList != null && companyMaterialList.size() > 0, "物料信息为空");
			String materialCode = companyMaterialList.get(0).getMaterialCode();
			orderInfoDetail.setMaterialCode(materialCode);
		}else {
			//有物料代码 就仅仅更新供方编号 仅用于投料单;
			companyMaterialMapper.updateCompanyMaterialByCodeForFeedOrder(orderInfoDetail);
			
			//判断订单与物料读颜色是否一致
			paramMap.put("materialCode", orderInfoDetail.getMaterialCode());
			CompanyMaterialTableBean cmtb = companyMaterialMapper.getCompanyMaterialTableByMaterialCode(paramMap);
			this.isEqualIsReadColorByMaterialType(cmtb, orderInfoDetail, paramMap);
		}
		int row = feedOrderMapper.addOrderInfoDetail(orderInfoDetail);
		Assert.isTrue(row > 0, "新增订单信息失败");
	}

	/**
	 * 获取订单明细信息通过订单信息 @date 2018年10月11日 下午1:37:57 @author 李斌 @return Object @throws
	 */
	public DatatablesViewPageBean<OrderInfoDetailPojo> getOrderInfoDetailByDetail(Map<String, Object> map) {
		DatatablesViewPageBean<OrderInfoDetailPojo> datatablesViewPageBean = new DatatablesViewPageBean<OrderInfoDetailPojo>();
		int count = feedOrderMapper.getOrderInfoDetailByDetailCount(map);
		//原订单信息 
		List<OrderInfoDetailPojo> orderInfoDetailPojos = feedOrderMapper.getOrderInfoDetailByDetail(map);
		List<Integer> delteOrderId = new ArrayList<Integer>();
		Map<Integer,Integer[]> orderMap = new HashMap<Integer,Integer[]>();
		//替换被删除的订单明细记录
		int i = 0;
		int j = 0;
		for(OrderInfoDetailPojo orderInfoDetailPojo:orderInfoDetailPojos) {
			if(orderInfoDetailPojo.getIsBom()==1) {
				Map<String,Object> paramMap = new HashMap<String,Object>();
				paramMap.put("type", 9);
				paramMap.put("loginUserId", map.get("loginUserId"));
				paramMap.put("loginCompany", map.get("loginCompany"));
				List<String> approvalList = approvalService.getApprovalIdByLoginId(paramMap);
				orderInfoDetailPojo.setApprovalUserId(approvalList);
			}
			List<OrderInfoDetailBean> orderInfoDetailList = orderInfoDetailPojo.getOrderInfoDetailList();
			for(OrderInfoDetailBean orderInfoDetailBean:orderInfoDetailList) {
				if(orderInfoDetailBean.getType()==3) {
					delteOrderId.add(orderInfoDetailBean.getId());
					orderMap.put(orderInfoDetailBean.getId(), new Integer[]{i,j});
				}
				j++;
			}
			i++;
		}
		if(delteOrderId.size()>0) {
			//被删除的订单信息
			map.put("delteOrderId", delteOrderId);
			List<OrderInfoDetailBean> deleteOrderInfoList = feedOrderMapper.getOrderInfoDetailByDeleteDetail(map);
			for(OrderInfoDetailBean orderInfoDetailBean:deleteOrderInfoList) {
				Integer [] orderDetail = orderMap.get(orderInfoDetailBean.getId());
				OrderInfoDetailBean oldOrderInfoDetail = orderInfoDetailPojos.get(orderDetail[0]).getOrderInfoDetailList().get(orderDetail[1]);
				orderInfoDetailBean.setSpecialRemark(oldOrderInfoDetail.getSpecialRemark());
				orderInfoDetailBean.setType(oldOrderInfoDetail.getType());
				orderInfoDetailPojos.get(orderDetail[0]).getOrderInfoDetailList().set(orderDetail[1], orderInfoDetailBean);
			}
		}
		datatablesViewPageBean.setiTotalDisplayRecords(count);
		datatablesViewPageBean.setiTotalRecords(count);
		datatablesViewPageBean.setReturnData(orderInfoDetailPojos);
		return datatablesViewPageBean;
	}
	

	/**
	 * 修改订单明细信息 @date 2018年10月12日 下午2:38:43 @author 李斌 @return void @throws
	 */
	public  void updateOrderInfoDetail(Map<String, Object> map) {
		/**
		 * 提交修改申请逻辑 : 首先 插入一条my_apply 申请修改记录 状态 已审核 1 然后插入一条记录在表 order_info_detail_apply
		 * 中(改变后的订单物料信息),
		 */
		Assert.notNull(map.get("orderInfoDetail"), "申请修改后的订单信息为空");
		// 申请修改后的订单信息
		OrderInfoDetailBean applyOrderInfoDetail = JSONObject.parseObject(map.get("orderInfoDetail").toString(),
				OrderInfoDetailBean.class);
		Assert.notNull(map.get("orderInfoDetailId"), "原订单明细id为空");
		// 原订单信息
		OrderInfoDetailBean oldOrderInfoDetail = feedOrderMapper.getOrderInfoDetailById(map);
		Assert.notNull(oldOrderInfoDetail, "原订单明细为空");
		boolean isEqu = applyOrderInfoDetail.equals(oldOrderInfoDetail);
		if (isEqu) {
			throw new ServiceException("订单物料信息未改变");
		}
		//如果订单修改了投料数或者订单数
		if(!StringUtil.checkEqu(applyOrderInfoDetail.getFeedTotal(),oldOrderInfoDetail.getFeedTotal())) {
			Assert.isTrue((oldOrderInfoDetail.getSmallFeedTotal()!=null && 
					!oldOrderInfoDetail.getSmallFeedTotal().equals("")) ||
					oldOrderInfoDetail.getLineNo().equals("-1"), "该列投料数为公共行投料数.请去制单页面修改");
		}
		if(!StringUtil.checkEqu(applyOrderInfoDetail.getOrderTotal(),oldOrderInfoDetail.getOrderTotal())) {
			Assert.isTrue((oldOrderInfoDetail.getSmallOrderTotal()!=null && 
					!oldOrderInfoDetail.getSmallOrderTotal().equals("")) ||
					oldOrderInfoDetail.getLineNo().equals("-1"), "该列订单数为公共行订单数.请去制单页面修改");
		}
		applyOrderInfoDetail.setId(oldOrderInfoDetail.getId());
		// 将修改后的订单信息放入map
		map.put("applyOrderInfoDetail", applyOrderInfoDetail);
		// 放入老的订单信息
		map.put("oldOrderInfoDetail", oldOrderInfoDetail);
		map.put("type", "update");
		MyApplyBean oldMyApply = this.insertMyApply(map);
		map.put("myApplyBean", oldMyApply);
		this.insertOrderInfoDetailApply(map);
		//发送微信信息
		String titleText = "物料清单申请修改待审核";
		String titleType= "待审核信息";
		String bodyMessage = "物料清单申请修改待审核(请到电脑页面查询)";
		duplicateOrderUpdateRecordsService.sendUpdateOrderDetailMes(oldOrderInfoDetail.getOrderNo(),titleText,titleType,bodyMessage,true,map);
	}

	/**
	 * 审核订单明细信息 @date 2018年10月18日 上午10:12:39 @author 李斌 @return void @throws
	 */
	public void approvalOrderInfoDetail(Map<String, Object> map, int status, int type) {
		Assert.notNull(map.get("orderInfoDetailId"), "订单明细id为空");
		Assert.isTrue(type == 1 || type == 2, "审批类型type错误");
		// 原订单信息
		OrderInfoDetailBean oldOrderInfoDetail = feedOrderMapper.getOrderInfoDetailById(map);
		Assert.notNull(oldOrderInfoDetail, "订单明细记录为空");
		MyApplyBean oldMyApply = feedOrderMapper.getMyApply(oldOrderInfoDetail);
		Assert.notNull(oldMyApply, "申请记录为空");
		//设置状态
		oldMyApply.setStatus(status);
		Assert.isTrue(oldMyApply.getType().equals(2), "在订单修改的去订单页面审核");
		map.put("oldOrderInfoDetail", oldOrderInfoDetail);
		map.put("myApplyBean", oldMyApply);
		if (status == 1) {// 审核通过
			// 校验订单是否可退回
			this.checkPurchaseAndFeedOrder(map, true);
			// 插入order_info_detail_audit记录
			this.insertOrderInfoDetailAudit(map);
			// 获取修改订单信息
			oldOrderInfoDetail.setApplyId(oldMyApply.getId());
			OrderInfoDetailBean updateOrderInfoDetail = this.getOrderInfoDetailApplyByOrderApply(oldOrderInfoDetail);
			int row = 0;
			if (type == 1) {// 修改操作审核
				updateOrderInfoDetail.setId(oldOrderInfoDetail.getId());
				if(("".equals(updateOrderInfoDetail.getSmallFeedTotal())||updateOrderInfoDetail.getSmallFeedTotal()==null)
					&&!"".equals(updateOrderInfoDetail.getFeedTotal())) {
					updateOrderInfoDetail.setSmallFeedTotal(updateOrderInfoDetail.getFeedTotal());
				}
				if(("".equals(updateOrderInfoDetail.getSmallOrderTotal())||updateOrderInfoDetail.getSmallOrderTotal()==null)
						&&!"".equals(updateOrderInfoDetail.getOrderTotal())) {
					updateOrderInfoDetail.setSmallOrderTotal(updateOrderInfoDetail.getOrderTotal());
				}
				row = feedOrderMapper.updateOrderInfoDetail(updateOrderInfoDetail);
			} else if (type == 2) {
				row = feedOrderMapper.deleteOrderInfoDetail(oldOrderInfoDetail);
				this.updateOrderInfoDetailWaster(oldOrderInfoDetail);
			}
			//判断订单是否为制单页面添加并且行号是-1的
			if(oldOrderInfoDetail.getIsOpraterAdd().equals(0) && "-1".equals(oldOrderInfoDetail.getLineNo())) {
				OrderInfoDetailBean orderInfoDetail = feedOrderMapper.getOrderInfoTailByOrderInfoDetail(oldOrderInfoDetail);
				if(orderInfoDetail !=null) {
					int tailRow = 0;
					//修改
					if(type==1) {
						updateOrderInfoDetail.setId(orderInfoDetail.getId());
						tailRow = feedOrderMapper.updateOrderInfoTail(updateOrderInfoDetail);
					}else if(type==2) {
					//删除
						tailRow = feedOrderMapper.deleteOrderInfoTail(orderInfoDetail);
					}
					Assert.isTrue(tailRow > 0, "订单操作失败");
				}
			}
			Assert.isTrue(row > 0, "订单操作失败");
		}else {
			feedOrderMapper.deleteOrderInfoDetailWaste(oldOrderInfoDetail);
		}
	}

	/**
	 * 更新订单明细备份记录删除状态 @date 2018年10月18日 上午10:27:37 @author 李斌 @return void @throws
	 */
	private void updateOrderInfoDetailWaster(OrderInfoDetailBean oldOrderInfoDetail) {
		int row = feedOrderMapper.updateOrderInfoDetailWaster(oldOrderInfoDetail);
		Assert.isTrue(row > 0, "更新订单明细备份记录删除状态异常");
	}

	/**
	 * 更新oldMyApply @date 2018年10月18日 上午9:01:22 @author 李斌 @return void @throws
	 */
	private void updateMyApplyOnStatus(MyApplyBean oldMyApply) {
		int row = feedOrderMapper.updateMyApply(oldMyApply);
		Assert.isTrue(row > 0, "申请记录更新状态异常");
	}

	/**
	 * 根据MyApplyBean @date 2018年10月18日 上午8:32:23 @author 李斌 @return
	 * OrderInfoDetailBean @throws
	 */
	private OrderInfoDetailBean getOrderInfoDetailApplyByOrderApply(OrderInfoDetailBean orderInfoDetailBeanApply) {
		OrderInfoDetailBean orderInfoDetailApply = feedOrderMapper.getOrderInfoDetailApplyByOrderInfoDetailBean(orderInfoDetailBeanApply);
		Assert.notNull(orderInfoDetailApply, "订单申请记录为空");
		return orderInfoDetailApply;
	}

	/**
	 * 校验该订单的采购与仓库,判断是否可修改与删除
	 * 
	 * @date 2018年10月16日 下午2:29:30
	 * @author 李斌
	 * @return void @throws
	 */
	private int checkPurchaseAndFeedOrder(Map<String, Object> map, boolean check) {
		/**
		 * 判断是否生成投料单
		 */
		OrderInfoDetailBean orderInfoDetailBean = (OrderInfoDetailBean) map.get("oldOrderInfoDetail");
		MyApplyBean applyBean = (MyApplyBean)map.get("myApplyBean");
		orderInfoDetailBean.setApplyId(applyBean.getId());
		OrderInfoDetailBean orderInfoDetailApplyBean = feedOrderMapper.getOrderInfoDetailApplyByOrderInfoDetailBean(orderInfoDetailBean);
		if(orderInfoDetailBean.getMaterialCode()==(orderInfoDetailApplyBean.getMaterialCode())
				&&orderInfoDetailBean.getColor()==(orderInfoDetailApplyBean.getColor())
				&&orderInfoDetailBean.getMaterialModel()==(orderInfoDetailApplyBean.getMaterialModel())
				&&orderInfoDetailBean.getFeedTotal()==(orderInfoDetailApplyBean.getFeedTotal())
				&&orderInfoDetailBean.getYltsTotal()==(orderInfoDetailApplyBean.getYltsTotal())
				&&orderInfoDetailBean.getColorDescription()!=(orderInfoDetailApplyBean.getColorDescription())) {
			//只是颜色描述改了
			check=false;
		}
		Assert.notNull(orderInfoDetailBean, "订单明细信息为空");
		Assert.isTrue(orderInfoDetailBean.getOrderNo() != null && !orderInfoDetailBean.getOrderNo().equals(""),
				"订单编号为空");
		Assert.isTrue(orderInfoDetailBean.getLineNo() != null && !orderInfoDetailBean.getLineNo().equals(""), "行号为空");
		Assert.isTrue(orderInfoDetailBean.getMaterialFactory() != null
				&& !orderInfoDetailBean.getMaterialFactory().equals(""), "仓位为空");
		Assert.isTrue(
				orderInfoDetailBean.getMaterialType() != null && !orderInfoDetailBean.getMaterialType().equals(""),
				"物料类型为空");
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("orderNo", orderInfoDetailBean.getOrderNo());
		paramMap.put("lineNo", orderInfoDetailBean.getLineNo());
		paramMap.put("materialFactory", orderInfoDetailBean.getMaterialFactory());
		paramMap.put("materialType", orderInfoDetailBean.getMaterialType());
		paramMap.put("loginCompany", map.get("loginCompany"));
		List<FeedOrderDetailBean> feedOrderDetailList = feedOrderMapper.getFeedOrderDetailByOrderInfoDetail(paramMap);
		if (check) {
			if(feedOrderDetailList !=null && feedOrderDetailList.size()>0) {
				StringBuffer stringBuffer = new StringBuffer();
				for(FeedOrderDetailBean feedOrderDetailBean:feedOrderDetailList) {
					stringBuffer.append("行号: "+feedOrderDetailBean.getLineNo()+",物料类型: "+feedOrderDetailBean.getMaterialType()+",仓位: "+feedOrderDetailBean.getMaterialFactory()+"<br>");
					Map retrunMap = new HashMap<>();
					retrunMap.put("status", 3);// 3 退回
					retrunMap.put("loginUserId", map.get("loginUserId"));
					retrunMap.put("loginCompany", map.get("loginCompany"));
					retrunMap.put("loginUserName", map.get("loginUserName"));
					JSONArray jsonArray = new JSONArray();
					JSONObject object = new JSONObject();
					object.put("id", feedOrderDetailBean.getId());
					object.put("approvalReason", "系统自动退回审核");
					jsonArray.add(object);
					retrunMap.put("beanArray", jsonArray.toString());
					//查询有没有采购单
					if (feedOrderDetailBean.getIsBuild().equals(1)) {
						Map<String, Object> mapPurchaseOrder = new HashMap<>();
						mapPurchaseOrder.put("feedDetailId", feedOrderDetailBean.getId());
						mapPurchaseOrder.put("loginCompany", map.get("loginCompany"));
						String purchaseDetailId = orderCreateMapper.getPurchaseOrderDetailIdByFeedDetailId(mapPurchaseOrder);
						//校验采购单能否直接退回 库存可用数-（取消订单的采购数-占用数）<0  
						checkPurchaseOrderApprovalBack(purchaseDetailId,1,map.get("loginCompany").toString());
						//throw new ServiceException("该投料单已生成采购单,请打生产订单修改单后,退回采购单 订单编号 :" + orderId);
						Map<String, String> approvalPurchaseOrderMap = new HashMap<>();
						approvalPurchaseOrderMap.put("purchaseDetailId", purchaseDetailId);
						approvalPurchaseOrderMap.put("type", "1");
						approvalPurchaseOrderMap.put("name", map.get("loginUserName").toString());
						approvalPurchaseOrderMap.put("orderId", feedOrderDetailBean.getOrderId());
						approvalPurchaseOrderMap.put("approvalReason", "物料信息修改系统自动退回");
						approvalPurchaseOrderMap.put("loginUserId", map.get("loginUserId").toString());
						approvalPurchaseOrderMap.put("loginUserName", map.get("loginUserName").toString());
						approvalPurchaseOrderMap.put("loginCompany",  map.get("loginCompany").toString());
						purchaseOrderService.approvalPurchaseOrder(approvalPurchaseOrderMap,2);
						continue;
					}
					orderService.allApprovalFeedOrder(retrunMap);
				}
				//throw new ServiceException("订单已生成投料单,请先退回投料单,投料单未查询到,请到采购单查询.<br>"+stringBuffer.toString());
			}
		}
		if (feedOrderDetailList == null || feedOrderDetailList.size() < 1) {
			return 1;// 未生成
		} else {
			return 0;// 已生成
		}
	}

	/**
	 * 订单明细查重 @date 2018年10月12日 下午2:44:30 @author 李斌 @return void @throws
	 */
	private List<OrderInfoDetailBean> duplicateCheck(OrderInfoDetailBean orderInfoDetailBean) {
		Assert.notNull(orderInfoDetailBean.getOrderNo(), "订单编号为空");
		Assert.notNull(orderInfoDetailBean.getMaterialType(), "物料类型为空");
		Assert.notNull(orderInfoDetailBean.getMaterialFactory(), "仓位为空");
		List<OrderInfoDetailBean> orderInfoDetailList = feedOrderMapper
				.getOrderInfoDetailCheckDuplicate(orderInfoDetailBean);
		return orderInfoDetailList;
	}

	/**
	 * 插入修改申请记录 @date 2018年10月15日 下午4:09:58 @author 李斌 @return void @throws
	 */
	private MyApplyBean insertMyApply(Map<String, Object> map) {
		/**
		 * specialRemark 修改信息 行号&物料类型&仓位| 类型格式 status 状态 -1审核中 -2申请撤销 0退回 1审核成功 order_no
		 * 订单编号 type 1:订单申请修改,2:投料单页面修改
		 */
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		OrderInfoDetailBean orderInfoDetailBean = (OrderInfoDetailBean) map.get("oldOrderInfoDetail");
		Assert.notNull(orderInfoDetailBean, "订单信息为空");
		// 查询该订单是否有已经在申请的记录了 status = -1 and 订单编号 最后一条
		MyApplyBean oldMyApply = feedOrderMapper.getMyApply(orderInfoDetailBean);
		MyApplyBean myApplyBean = new MyApplyBean();
		String specialRemark = orderInfoDetailBean.getLineNo() + "&" + orderInfoDetailBean.getMaterialType() + "&"
				+ orderInfoDetailBean.getMaterialFactory();
		if (oldMyApply == null) {
			String applyId = dingTalkMapper.getApprovalNo("Apply");
			myApplyBean.setId(applyId);
			myApplyBean.setOrderNo(orderInfoDetailBean.getOrderNo());
			myApplyBean.setType(2);
			myApplyBean.setStatus(-1);
			myApplyBean.setSpecialRemark(specialRemark+"|");
			myApplyBean.setRemark((String) map.get("remark"));
			myApplyBean.setApplyTime(simpleDateFormat.format(new Date()));
			myApplyBean.setApplyUser(map.get("loginUserName").toString());
			myApplyBean.setApplyUserId(map.get("loginUserId").toString());
			int row = feedOrderMapper.addMyApply(myApplyBean);
			Assert.isTrue(row > 0, "插入订单修改申请记录失败");
			oldMyApply = myApplyBean;
		} else {// 如果,有已经申请中的了.两个方案 :1 覆盖之前的申请记录 2 在原记录上,添加这次的记录
				// 方案2
			Assert.isTrue(oldMyApply.getApplyUserId().equals(map.get("loginUserId").toString()), oldMyApply.getApplyUser()+"已申请修改该订单了.您不能再次申请修改了");
			Assert.isTrue(oldMyApply.getType().equals(2), "该订单正在申请修改中,请到订单页面查看");
			boolean flag = true;
			String[] allRemark = oldMyApply.getSpecialRemark().split("\\|");
			for (String remark : allRemark) {
				if (specialRemark.equals(remark)) {
					flag = false;
					break;
				}
			}
			if (flag) {
				specialRemark = oldMyApply.getSpecialRemark() + specialRemark+"|";
				oldMyApply.setSpecialRemark(specialRemark);
				int row = feedOrderMapper.updateMyApply(oldMyApply);
				Assert.isTrue(row > 0, "插入申请记录失败");
			} else {
				specialRemark = oldMyApply.getSpecialRemark();
			}
		}
		return oldMyApply;
	}

	/**
	 * 插入修改申请后订单信息记录 @date 2018年10月16日 上午8:24:52 @author 李斌 @return void @throws
	 */
	private OrderInfoDetailBean insertOrderInfoDetailApply(Map<String, Object> map) {
		/**
		 * 内容与原订单格式类似 只是加入了apply_id, apply_id 为 myApplyBean的id
		 */
		// 修改后的订单信息
		OrderInfoDetailBean orderInfoDetailApply = (OrderInfoDetailBean) map.get("applyOrderInfoDetail");
		// 原订单记录
		OrderInfoDetailBean oldOrderInfoDetail = (OrderInfoDetailBean) map.get("oldOrderInfoDetail");
		// 置换订单修改信息(返回orderInfoDatailApply)
		orderInfoDetailApply = this.exchangeOrderInfoDetailApply(oldOrderInfoDetail, orderInfoDetailApply, map);
		// 申请修改记录
		MyApplyBean myApplyBean = (MyApplyBean) map.get("myApplyBean");
		orderInfoDetailApply.setApplyId(myApplyBean.getId());
		OrderInfoDetailBean oldOrderInfoDetailApply = feedOrderMapper.getOrderInfoDetailApplyByOrderInfoDetailBean(orderInfoDetailApply);
		if(oldOrderInfoDetailApply==null) {
			int row = feedOrderMapper.addOrderInfoDetailApply(orderInfoDetailApply);
			Assert.isTrue(row > 0, "插入修改申请后订单信息失败");
		}
		return orderInfoDetailApply;
	}

	/**
	 * 置换订单信息 @date 2018年10月16日 上午10:17:18 @author 李斌 @return
	 * OrderInfoDetailBean @throws
	 */
	private OrderInfoDetailBean exchangeOrderInfoDetailApply(OrderInfoDetailBean oldOrderInfoDetail,
			OrderInfoDetailBean orderInfoDetailApply, Map<String, Object> map) {
		// 如果订单信息里面没有物料代码. 说明该物料是新物料
		Assert.notNull(map.get("type"), "操作类型为空");
		if ("update".equals(map.get("type").toString())) {// 更新订单
			if (orderInfoDetailApply.getMaterialCode() == null || orderInfoDetailApply.getMaterialCode().equals("")) {
				Assert.notNull(map.get("materialData"), "物料信息为空");
				CompanyMaterialTableBean companyMaterialTableBean = JSONObject
						.parseObject(map.get("materialData").toString(), CompanyMaterialTableBean.class);
				// 判断物料类型
				Assert.isTrue(companyMaterialTableBean.getMaterialType() != null
						&& !companyMaterialTableBean.getMaterialType().equals(""), "物料类型为空");
				if(oldOrderInfoDetail.getMaterialFactory().equals("2")) {
					companyMaterialTableBean.setDefaultWarehouse("辅料仓");
				}
				if(!"付".equals(companyMaterialTableBean.getUnit())) {
					companyMaterialTableBean.setIsEquals(0);
				}else {
					companyMaterialTableBean.setIsEquals(1);
				}
				//不再判断是否读取颜色
				/*if(oldOrderInfoDetail.getIsReadColor()==2) {
					companyMaterialTableBean.setColor("");
					companyMaterialTableBean.setColorDescription("");
				}*/
				MyUser myuser = new MyUser();
				myuser.setCompany(map.get("loginCompany").toString());
				myuser.setUserId(map.get("loginUserId").toString());
				myuser.setUserName(map.get("loginUserName").toString());
				//判断订单与物料读颜色是否一致
				isEqualIsReadColorByMaterialType(companyMaterialTableBean,oldOrderInfoDetail,map);
				//添加物料
				List<CompanyMaterialTableBean> list = basicDataService.insertCompanyMaterial(companyMaterialTableBean,
						myuser);
				Assert.isTrue(list != null && list.size() > 0, "添加物料失败");
				map.put("id", list.get(0).getId());
				List<CompanyMaterialTableBean> companyMaterialList = basicDataService.getCompanyMaterialDetail(map);
				Assert.isTrue(companyMaterialList != null && companyMaterialList.size() > 0, "物料信息为空");
				String materialCode = companyMaterialList.get(0).getMaterialCode();
				orderInfoDetailApply.setMaterialCode(materialCode);
			}else {
				//有物料代码 就仅仅更新供方编号 仅用于投料单;
				companyMaterialMapper.updateCompanyMaterialByCodeForFeedOrder(orderInfoDetailApply);
			}
			int isReadColor = oldOrderInfoDetail.getIsReadColor();
			oldOrderInfoDetail.setFeedTotal(orderInfoDetailApply.getFeedTotal());
			oldOrderInfoDetail.setOrderTotal(orderInfoDetailApply.getOrderTotal());
			oldOrderInfoDetail.setYltsTotal(orderInfoDetailApply.getYltsTotal());
			oldOrderInfoDetail.setSmallFeedTotal(orderInfoDetailApply.getSmallFeedTotal());
			oldOrderInfoDetail.setSmallOrderTotal(orderInfoDetailApply.getSmallOrderTotal());
			/*if(isReadColor==1) {
				oldOrderInfoDetail.setColor(orderInfoDetailApply.getColor());
				oldOrderInfoDetail.setColorDescription(orderInfoDetailApply.getColorDescription());
			}*/
			//不再判断是否读取颜色
			oldOrderInfoDetail.setColor(orderInfoDetailApply.getColor());
			oldOrderInfoDetail.setColorDescription(orderInfoDetailApply.getColorDescription());
			//判断订单与物料读颜色是否一致
			Map<String,Object> materialMap = new HashMap<String,Object>();
			materialMap.put("loginCompany", map.get("loginCompany"));
			materialMap.put("materialCode", orderInfoDetailApply.getMaterialCode());
			CompanyMaterialTableBean cmtb = companyMaterialMapper.getCompanyMaterialTableByMaterialCode(materialMap);
			isEqualIsReadColorByMaterialType(cmtb,oldOrderInfoDetail,map);
		} else if ("delete".equals(map.get("type").toString())) {// 删除订单
			oldOrderInfoDetail.setFeedTotal(null);
			oldOrderInfoDetail.setYltsTotal(null);
			oldOrderInfoDetail.setOrderTotal(null);
			oldOrderInfoDetail.setColor(orderInfoDetailApply.getColor());
			oldOrderInfoDetail.setColorDescription(orderInfoDetailApply.getColorDescription());
		}
		oldOrderInfoDetail.setMaterialCode(orderInfoDetailApply.getMaterialCode());
		oldOrderInfoDetail.setMaterialModel(orderInfoDetailApply.getMaterialModel());
		oldOrderInfoDetail.setMaterialName(orderInfoDetailApply.getMaterialName());
		return oldOrderInfoDetail; 
	}

	/**
	 * 插入订单申请通过后的原订单信息+applyId @date 2018年10月16日 下午3:56:37 @author 李斌 @return
	 * void @throws
	 */
	private void insertOrderInfoDetailAudit(Map<String, Object> map) {
		// 原订单信息
		OrderInfoDetailBean orderInfoDetailAudit = (OrderInfoDetailBean) map.get("oldOrderInfoDetail");
		// 插入申请记录
		MyApplyBean myApplyBean = (MyApplyBean) map.get("myApplyBean");
		// 插入原订单信息
		orderInfoDetailAudit.setApplyId(myApplyBean.getId());
		int row = feedOrderMapper.addOrderInfoDetailAudit(orderInfoDetailAudit);
		Assert.isTrue(row > 0, "插入订单申请修改后信息失败");
	}

	public void insertMyAudit(Map<String, Object> map) {
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		// 插入申请记录
		MyApplyBean myApplyBean = (MyApplyBean) map.get("myApplyBean");
		MyAuditBean myAuditBean = new MyAuditBean();
		myAuditBean.setOrderNo(myApplyBean.getOrderNo());
		myAuditBean.setAuditUser(myApplyBean.getApplyUser());
		myAuditBean.setAuditTime(simpleDateFormat.format(new Date()));
		myAuditBean.setSpecialRemark(myApplyBean.getSpecialRemark());
		myAuditBean.setRemark(myApplyBean.getRemark());
		myAuditBean.setStatus(myApplyBean.getStatus());
		myAuditBean.setType(2);
		myAuditBean.setApplyId(myApplyBean.getId());
		int row = feedOrderMapper.addMyAudit(myAuditBean);
		Assert.isTrue(row > 0, "插入订单申请通过后的原订单申请信息失败");
	}

	/**
	 * 删除订单物料信息 @date 2018年10月17日 上午9:17:54 @author 李斌 @return void @throws
	 */
	public void deleteOrderInfoDetail(Map<String, Object> map) {
		/**
		 * 删除逻辑 : 与更新相同,只是把物料信息清空,只剩下物料类型即可 提交修改申请逻辑 : 首先 插入一条my_apply 申请修改记录 状态 已审核 1
		 * 然后插入一条记录在表 order_info_detail_apply 中(改变后的订单物料信息),
		 */
		Assert.notNull(map.get("applyOrderInfoDetail"), "申请修改后的订单信息为空");
		// 申请修改后的订单信息
		OrderInfoDetailBean applyOrderInfoDetail = JSONObject.parseObject(map.get("applyOrderInfoDetail").toString(),
				OrderInfoDetailBean.class);
		Assert.notNull(map.get("orderInfoDetailId"), "原订单明细id为空");
		// 原订单信息
		OrderInfoDetailBean oldOrderInfoDetail = feedOrderMapper.getOrderInfoDetailById(map);
		Assert.notNull(oldOrderInfoDetail, "原订单明细为空");
		// 将修改后的订单信息放入map
		map.put("applyOrderInfoDetail", applyOrderInfoDetail);
		map.put("oldOrderInfoDetail", oldOrderInfoDetail);
		MyApplyBean oldMyApply = this.insertMyApply(map);
		map.put("type", "delete");
		// 校验是否退回投料采购单
		map.put("myApplyBean", oldMyApply);
		// 备份订单明细信息
		int orderWasteRow = feedOrderMapper.addOrderInfoDetailWaste(oldOrderInfoDetail);
		this.insertOrderInfoDetailApply(map);
		Assert.isTrue(orderWasteRow > 0, "备份订单明细信息失败");
		//发送微信信息
		String titleText = "物料清单申请修改待审核";
		String titleType= "待审核信息";
		String bodyMessage = "物料清单申请修改待审核(请到电脑页面查询)";
		duplicateOrderUpdateRecordsService.sendUpdateOrderDetailMes(oldOrderInfoDetail.getOrderNo(),titleText,titleType,bodyMessage,true,map);
	}

	/**
	 * 校验订单信息是否生成投料单或采购单 @date 2018年10月18日 下午2:36:27 @author 李斌 @return int @throws
	 */
	/*public int checkOrderInfoDetail(Map<String, Object> map) {
		Assert.notNull(map.get("orderInfoDetailId"), "原订单明细id为空");
		// 原订单信息
		OrderInfoDetailBean oldOrderInfoDetail = feedOrderMapper.getOrderInfoDetailById(map);
		map.put("oldOrderInfoDetail", oldOrderInfoDetail);
		return this.checkPurchaseAndFeedOrder(map, false);
	}*/

	/**
	 * 插入Apply记录 @date 2018年10月18日 下午3:03:19 @author 李斌 @return void @throws
	 */
	public void toReturnPurchaseAndFeed(Map<String, Object> map) {
		Assert.notNull(map.get("orderInfoDetailId"), "原订单明细id为空");
		// 原订单信息
		OrderInfoDetailBean oldOrderInfoDetail = feedOrderMapper.getOrderInfoDetailById(map);
		map.put("oldOrderInfoDetail", oldOrderInfoDetail);
		this.insertMyApply(map);
	}
	
	/**
	 * 获取申请修改后的记录
	* @date 2018年10月20日 下午4:55:43 
	* @author 李斌
	* @return Object 
	* @throws
	 */
	public List<OrderInfoDetailBean> getOrderInfoDetailApply(Map<String, Object> map) {
		// 原订单信息
		Assert.notNull(map.get("orderNo"),"订单编号为空");
		map.put("orderId", map.get("orderNo"));
		String applyId = orderMapper.getApplyIdByOrderId(map);
		Assert.notNull(applyId,"申请记录为空");
		map.put("applyId", applyId);
		List<OrderInfoDetailBean> orderInfoDetailBeanApplyList = feedOrderMapper.getOrderInfoDetailApplyByApplyId(map);
		return orderInfoDetailBeanApplyList;
	}
	
	public void approvalOrderInfoAfter(Map<String,Object> map,int status) {
		Assert.notNull(map.get("orderInfoDetailId"), "原订单明细id为空");
		// 原订单信息
		OrderInfoDetailBean oldOrderInfoDetail = feedOrderMapper.getOrderInfoDetailById(map);
		MyApplyBean myApplyBean = feedOrderMapper.getMyApply(oldOrderInfoDetail);
		myApplyBean.setStatus(status==2?0:status);
		map.put("myApplyBean",myApplyBean);
		this.insertMyAudit(map);
		this.updateMyApplyOnStatus(myApplyBean);
	}

	public void updateOrderInfoDetailByStatus(Map<String, Object> map,int status) {
		Assert.notNull(map.get("orderInfoDetailList"), "订单明细信息为空");
		List<OrderInfoDetailBean> orderInfoDetailList = JSONArray.parseArray(map.get("orderInfoDetailList").toString(),OrderInfoDetailBean.class);
		map.put("orderInfoDetailId", orderInfoDetailList.get(0).getId());
		OrderInfoDetailBean orderInfoDetail = feedOrderMapper.getOrderInfoDetailById(map);
		boolean canApproval = true;
		MyApplyBean myApplyBean = feedOrderMapper.getMyApply(orderInfoDetail);
		Map<String,Object> paramMap = new HashMap<String,Object>();
		paramMap.put("type", 9);
		paramMap.put("loginUserId", map.get("loginUserId"));
		paramMap.put("loginCompany", map.get("loginCompany"));
		List<String> approvalList = approvalService.getApprovalIdByLoginId(paramMap);
		canApproval =  approvalList.contains(myApplyBean.getApplyUserId());
		Assert.isTrue(canApproval, "暂无权限审核改物料清单");
		for(OrderInfoDetailBean orderInfoDetailBean:orderInfoDetailList) {
			map.put("orderInfoDetailId", orderInfoDetailBean.getId());
			this.approvalOrderInfoDetail(map, status, orderInfoDetailBean.getType());
		}
		this.approvalOrderInfoAfter(map,status);
	}
	
	/**
	 * 判断订单的物料类型与物料的物料类型读颜色与否是不是一致
	* @date 2018年10月27日 下午3:33:25 
	* @author 李斌
	* @return void 
	* @throws
	 */
	public void isEqualIsReadColorByMaterialType(CompanyMaterialTableBean companyMaterialTableBean,OrderInfoDetailBean orderInfoDetailBean,Map<String,Object> map) {
		int orderIsReadColor = 1;
		int materialIsReadColor = 1;
		//判断订单的物料类型与物料的物料类型是不是一致,并且都是读颜色或者不读颜色
		if(orderInfoDetailBean.getIsReadColor() !=0) {
			orderIsReadColor = orderInfoDetailBean.getIsReadColor();
		}
		// 校验该物料类型是否需要颜色
		if((companyMaterialTableBean.getColor()==null || companyMaterialTableBean.getColor().equals("")) && (companyMaterialTableBean.getColorDescription()==null || companyMaterialTableBean.getColorDescription().equals(""))) {
			materialIsReadColor = 2;
		}
		//不校验是否读取颜色
		//Assert.isTrue(orderIsReadColor==materialIsReadColor, "订单为"+(orderIsReadColor==2?"不读":"读")+"颜色,所选的物料"+(materialIsReadColor==2?"不读":"读")+"颜色");
	}
	
	//校验采购单能否直接退回 20200331
	public  void checkPurchaseOrderApprovalBack(String purchaseOrderDetailId,int type,String company) {
		if(type == 1) {//订单采购退回
			Map<String, Object> map = new HashMap<>();
			map.put("ids", new String[] {purchaseOrderDetailId});
			map.put("type", type);
			List<PurchaseOrderDetailPojo> pojos = purchaseOrderMapper.getPurchaseOrderByPageData(map);
			//通过采购单detailId获取采购数量和物料代码
			BigDecimal purchaseCount = new BigDecimal(pojos.get(0).getPurchaseCount().toString());
			String materialCode = pojos.get(0).getMaterialCode();
			BigDecimal availableCount = new BigDecimal(pojos.get(0).getAvailableCount().toString());//占用数
			BigDecimal useableCount = new BigDecimal(purchaseOrderService.getMaterialAvailableCount(materialCode , company).toString());//库存可用数
			
			//校验采购单能否直接退回 库存可用数-（取消订单的采购数-占用数）<0 并且有占用 并且 投料数和采购数不等的情况系
			double backTotal = useableCount.subtract(purchaseCount).add(availableCount).doubleValue();
			if (backTotal < 0 && availableCount.doubleValue() > 0 && pojos.get(0).getFeedOrderFeedCount()!=null && pojos.get(0).getFeedOrderFeedCount()!=null) {
				BigDecimal feedOrderFeedCount = new BigDecimal(pojos.get(0).getFeedOrderFeedCount().toString());
				BigDecimal actualFeedCount = new BigDecimal(pojos.get(0).getActualFeedCount().toString());
				if(feedOrderFeedCount.doubleValue()!=actualFeedCount.doubleValue()) {
					throw new ServiceException("采购单不能退回,请先补充物料数量"+Math.abs(backTotal)+"。库存可用数:"+useableCount+",占用数:"+availableCount+",采购数:"+purchaseCount);
				}
			}
		}
		if(type == 2) {//库存采购退回
			
		}
		
		
		
	}
}
